<template>
  <!-- 顶部返回吸顶条 -->
  <zcb-head
    :showButton="true"
    :title="(componentObject?.ticketName || ticketName || '') + '-' + (componentObject?.ticketCode || ticketCode || '')"
    v-if="componentShow"
  >
    <template #btn>
      <el-button
        v-permission="['home.approvalCenter.ISubmitted.edit']"
        v-if="formData.status == 'UNDER_APPROVAL' && route.query?.sourceType !== 'toBeApproved'"
        type="info"
        @click.stop="btnsClick(7)"
        >{{ t('keys.withdraw') }}</el-button
      >
    </template>
  </zcb-head>
  <div class="cont" v-loading="loading">
    <div class="cont_left">
      <component :is="current.com" v-if="componentShow" :componentObject="componentObject" :docConfigLineList="docConfigLineList"></component>
    </div>
    <div class="cont_right">
      <!-- 有操作按钮的审批记录 -->
      <approvalRecord
        :formData="formData"
        :approvalRecordData="approvalRecordData"
        :activities="activities"
        :approvalAction="approvalAction"
        @flowchartShow="flowchartShow"
        @btnsClick="btnsClick"
      ></approvalRecord>
    </div>
    <zcb-dialog
      v-model="dialogObj.visible"
      :title="t('keys.process_config')"
      class="custom"
      width="70%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :showClose="true"
    >
      <zcb-flow-chart v-if="dialogObj.visible" :nodeConfig="nodeConfig"></zcb-flow-chart>
    </zcb-dialog>
    <textarea-model
      v-if="textareaModelfalg"
      ref="textareaModelChild"
      :autosize="{ minRows: 5, maxRows: 5 }"
      :textareaModelObj="textareaModelObj"
      :descriptionFalg="descriptionFalg"
      @textareaModel-submit="textareaModelSubmit"
      @closeModel="textareaModelfalg = false"
    ></textarea-model>
    <co-model
      v-if="textareaModelfalg"
      ref="coModelChild"
      :coModelObj="coModelObj"
      @coModel-submit="coModelSubmit"
      @closeModel="textareaModelfalg = false"
    ></co-model>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, markRaw, defineAsyncComponent, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ERR_OK } from 'config/statusCode'
import { getUserInfo } from 'utils/headerToken'
import { getprocessRuntimeVariableApi } from 'api/personalCenter'
import { docConfigCodelineList } from 'api/personalCenter'
import approvalRecord from './component/approvalRecord'
import { mySubmittedRevokeApi } from 'api/personalCenter'

import {
  getApproveDetailApi,
  processApproveTaskPassApi,
  processApproveTaskRefuseApi,
  processApproveTasktRansferApi,
  agreeAndAddSignApi,
  processApproveTaskCcApi,
  processApproveTaskpreAddSignApi,
  processApproveTaskRejectApi,
  beforeSignApi,
  afterSignApi
} from 'api/personalCenter'
// import { nodeConfig as nodeConfigs } from 'components/flow-chart/hooks/json'

import textareaModel from './component/textareaModel.vue'
import coModel from './component/coModel.vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文
const route = useRoute()
const nodeConfig = ref({})
const instanceId = ref(route.query.instanceId || '')
const ticketCode = ref(route.query.ticketCode || '')
const ticketName = ref(route.query.ticketName || '')
const processApproverTaskId = ref(route.query.processApproverTaskId || '')
// 定义初始组件地址
let current = reactive({
  com: markRaw(defineAsyncComponent(() => import(`views/personalCenter/componentForm/test.vue`)))
})
// // 切换组件
const switchComponent = (component) => {
  // component组件名称
  console.log('当前组件地址：', `views/personalCenter/componentForm/${component}.vue`)
  current.com = markRaw(defineAsyncComponent(() => import(`views/personalCenter/componentForm/${component}.vue`)))
}
const approveComment = ref(t('keys.approve_comment'))

const docConfigLineList = ref([]) // 返回的渲染页面数据和值
const componentObject = ref({
  attachment: {}, // 附件
  baseData: {}, // 基本信息数据
  headInfo: [], // 基本信息UI
  baseDataLineList: {}, // 行信息数据
  lineInfo: [] // 行信息UI
}) // 对应页面的值
const componentShow = ref(false) // 是否展示动态组件

const getflowtaskProcessVariables = async () => {
  // 组件的UI循环list和 value对象值
  const { code, data } = await docConfigCodelineList({ docConfigCode: formData.docConfigCode })
  if (code === ERR_OK) {
    let docList = data.docConfigLineList || []
    docConfigLineList.value = JSON.parse(JSON.stringify(docList))
    switchComponent(data.fromUrl)
  }

  let param = {
    variableKey: ''
  }
  const fromUrl = data.fromUrl
  getprocessRuntimeVariableApi(param, instanceId.value).then((res) => {
    if (res.code === ERR_OK) {
      if (res.data?.templateCode) {
        componentObject.value = { ...componentObject.value, ...res.data }
        delete componentObject.value.attachment
        delete componentObject.value.baseData
        delete componentObject.value.headInfo
        delete componentObject.value.baseDataLineList
        delete componentObject.value.lineInfo
      } else {
        if (fromUrl === 'performancePreview') {
          componentObject.value = JSON.parse(res.data?.approveData)
          console.log(componentObject)
        } else {
          componentObject.value.attachment = res.data?.attachment ? JSON.parse(res.data?.attachment) : {} // 附件
          componentObject.value.baseData = res.data?.baseData ? JSON.parse(res.data?.baseData) : {} // 基本信息数据
          componentObject.value.headInfo = res.data?.headInfo ? JSON.parse(res.data?.headInfo) : [] // 基本信息UI
          componentObject.value.baseDataLineList = res.data?.baseDataLineList ? JSON.parse(res.data?.baseDataLineList) : {} // 行信息数据
          componentObject.value.lineInfo = res.data?.lineInfo ? JSON.parse(res.data?.lineInfo) : [] // 行信息UI
        }
      }
    }
    console.log(componentObject.value)
    componentShow.value = true
  })
}

// 流程记录列表
const loading = ref(false)
const activities = ref([])
const formData = reactive({}) // 基本信息
const flowViewerList = ref([]) // 走过的节点
const approvalAction = ref([]) // 审批节点操作按钮的展示

const getApproveDetail = async () => {
  loading.value = true
  //  获取审批详情
  const { code, data } = await getApproveDetailApi({ ticketCode: ticketCode.value }, instanceId.value)
  if (code === ERR_OK) {
    Object.assign(formData, data.instanceDetail || {}, { nodeId: data.approvalRecordsList[0][data.approvalRecordsList?.length]?.nodeId }) // 基本信息
    activities.value = data.approvalRecordsList || [] // 流程记录列表
    nodeConfig.value = data.processVersionDetailDTO?.nodeOrder || {} // 流程图tree
    approvalAction.value = data.instanceDetail?.approvalAction || []
    let isStatusTrue = false
    activities.value.forEach((activity) => {
      activity.forEach((item) => {
        // pass -true 走过的节点  false(待审批、异常)没走过
        if (item.nodeType === 'startNode') {
          // 开始节点
          item.type = 'primary'
          item.icon = ''
          item.color = ''
          item.hollow = true
        } else if (item.pass && item.nodeType !== 'startNode') {
          // true 走过的节点
          item.type = ''
          item.icon = 'Check'
          item.color = '#48D000'
        } else {
          // status - true 正常 fasle 异常
          if (!item.status) {
            // fasle 异常
            item.type = ''
            item.icon = 'Close'
            item.color = 'red'
          } else if (!isStatusTrue && item.status) {
            isStatusTrue = true
            //true 正常
            item.type = 'warning'
            item.icon = 'Clock'
            item.color = '#2878ff'
          } else {
            //等待
            item.type = 'warning'
            item.icon = 'More'
            item.color = '#999999'
          }
        }
      })
    })
    // 获取组件的 渲染key 和值
    if (formData?.docConfigCode) {
      getflowtaskProcessVariables()
    }

    // 取出最新一个审批节点
    getApprovalRecordData(data.approvalRecordsList)
    nextTick(() => {
      setTimeout(() => {
        let box = document.querySelector('.approval_record')
        box.scrollTo(1000, 100000) //滚动到距离元素顶部
      })
    })
  }
  loading.value = false
}
onMounted(() => {
  getApproveDetail()
})

const approvalRecordData = ref({})
const getApprovalRecordData = (list) => {
  if (list.length > 0) {
    let foreachList = list[list.length - 1]
    if (foreachList.length > 0) {
      for (var i = foreachList.length - 1; i >= 0; i--) {
        if (foreachList[i].nodeType == 'startNode') {
          approvalRecordData.value = foreachList[i]
          return
        }
      }
    }
  }
}
// 右侧按钮点击
const textareaModelfalg = ref(false)
const textareaModelObj = reactive({
  title: '',
  copywriting: '', // 文案
  copywritingBill: '' // span包裹的文案
})
const approvalActionList = ref([])
const textareaModelChild = ref(null)

const coModelChild = ref(null) // 1-前加签 2-同意并加签 3-转交 4-抄送
const coModelObj = reactive({
  title: '',
  copywriting: '', // 文案
  copywritingBill: '' // span包裹的文案
})

const btnsNum = ref(0)
const descriptionFalg = ref(true)
const btnsClick = (num) => {
  descriptionFalg.value = true
  textareaModelfalg.value = true
  //0-驳回 1-前加签 2-同意并加签 3-转交 4-抄送 5-拒绝 6-批准   7-撤回
  coModelObj.num = num
  if (num === 0) {
    textareaModelObj.title = t('keys.reject')
    textareaModelObj.copywriting = `${t('keys.Reject_process')}<span> ${ticketCode.value} - ${ticketName.value} </span>${t('keys.is_it')}`
    textareaModelObj.label = t('keys.approve_comment')
    nextTick(() => {
      textareaModelChild.value.showModel()
    })
  } else if (num === 1) {
    coModelObj.title = t('keys.Front_endorsement')
    coModelObj.labelOne = t('keys.Countersigned_by')
    coModelObj.labelTwo = t('keys.Reason_for_endorsement')
    coModelObj.labelThree = t('keys.approvalType')
    nextTick(() => {
      coModelChild.value.showModel()
    })
  } else if (num === 2) {
    coModelObj.title = t('keys.Approved_and_signed_later')
    coModelObj.labelOne = t('keys.Countersigned_by')
    coModelObj.labelTwo = t('keys.Reason_for_endorsement')
    coModelObj.labelThree = t('keys.approvalType')
    nextTick(() => {
      coModelChild.value.showModel()
    })
  } else if (num === 3) {
    coModelObj.title = t('keys.passed_on')
    coModelObj.labelOne = t('keys.Referee')
    coModelObj.labelTwo = t('keys.Reasonfor_transfer')
    nextTick(() => {
      coModelChild.value.showModel()
    })
  } else if (num === 4) {
    coModelObj.title = t('keys.Cc')
    coModelObj.labelOne = t('keys.Cc_on_man')
    coModelObj.labelTwo = t('keys.Cc_on_reason')
    nextTick(() => {
      coModelChild.value.showModel()
    })
  } else if (num === 5) {
    textareaModelObj.title = t('keys.reject')
    textareaModelObj.copywriting = `${t('keys.Reject_process')}<span> ${ticketCode.value} - ${ticketName.value} </span>${t('keys.is_it')}`
    textareaModelObj.label = t('keys.approve_comment')
    descriptionFalg.value = true
    nextTick(() => {
      textareaModelChild.value.showModel()
    })
  } else if (num === 6) {
    textareaModelObj.title = t('keys.approval')
    textareaModelObj.copywriting = `${t('keys.Approve_Process')}<span> ${ticketCode.value} - ${ticketName.value} </span>${t('keys.is_it')}`
    textareaModelObj.label = t('keys.approve_comment')
    descriptionFalg.value = false
    nextTick(() => {
      textareaModelChild.value.showModel()
    })
  } else if (num === 7) {
    // 撤回
    textareaModelObj.title = t('keys.withdraw')
    textareaModelObj.copywriting = `${t('keys.Whether_to_withdraw')} <span>${ticketCode.value} - ${ticketName.value}</span> ${t(
      'keys.Approval_process'
    )}？`
    nextTick(() => {
      textareaModelChild.value.showModel()
    })
  }
  btnsNum.value = num
}
// 0-驳回 5-拒绝 6-批准
const textareaModelSubmit = async (val) => {
  textareaModelfalg.value = false
  let approvalActionObj = {}
  // 从审批记录中 比对processApproverTaskId 是否存在 存在继续不存在提示报错
  if (activities.value.length > 0) {
    activities.value.forEach((aitem) => {
      if (formData.processInstanceId == aitem[0].processInstanceId) {
        aitem.forEach((bitem) => {
          if (formData.processInstanceId == bitem.processInstanceId && bitem?.recordDetail && bitem?.recordDetail.length > 0) {
            bitem.recordDetail.forEach((item) => {
              if (item.processApproverTaskId == processApproverTaskId.value) {
                approvalActionObj = {
                  nodeId: formData.nodeId,
                  processApproverTaskId: item.processApproverTaskId, // 流程审批任务id
                  processInstanceId: formData.processInstanceId, // 流程实例id
                  processRuntimeId: formData.processRuntimeId, // 流程运行节点id
                  operator: getUserInfo().empId || '' // 操作人
                }
              }
            })
          }
        })
      }
    })
  }

  let param = {
    approvalActionList: [approvalActionObj], // 流程实例id
    comment: val.description, // 审批意见
    tenantId: localStorage.getItem('tenantId'),
    transferPerson: val.empId // 转交人
  }
  if (btnsNum.value === 0) {
    const { code, data } = await processApproveTaskRejectApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.reject') + t('keys.success'))
      goBack()
    }
  } else if (btnsNum.value === 5) {
    const { code, data } = await processApproveTaskRefuseApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.reject') + t('keys.success'))
      goBack()
    }
  } else if (btnsNum.value === 6) {
    const { code, data } = await processApproveTaskPassApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.approval') + t('keys.success'))
      goBack()
    }
  } else if (btnsNum.value === 7) {
    let paramData = {
      empId: getUserInfo().empId,
      processInstanceId: formData.processInstanceId,
      revokeReason: val.description
    }
    // 撤回
    const { code, data } = await mySubmittedRevokeApi(paramData, formData.processInstanceId)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.withdraw_succeeded'))
      location.reload()
    }
  }
}
// 1-前加签 2-同意并加签 3-转交 4-抄送
const coModelSubmit = async (val) => {
  textareaModelfalg.value = false
  let approvalActionObj = {}
  // 从审批记录中 比对processApproverTaskId 是否存在 存在继续不存在提示报错
  if (activities.value.length > 0) {
    activities.value.forEach((aitem) => {
      if (formData.processInstanceId == aitem[0].processInstanceId) {
        aitem.forEach((bitem) => {
          if (formData.processInstanceId == bitem.processInstanceId && bitem?.recordDetail && bitem?.recordDetail.length > 0) {
            bitem.recordDetail.forEach((item) => {
              if (item.processApproverTaskId == processApproverTaskId.value) {
                approvalActionObj = {
                  nodeId: formData.nodeId, // 流程审批任务id
                  processApproverTaskId: item.processApproverTaskId, // 流程审批任务id
                  processInstanceId: formData.processInstanceId, // 流程实例id
                  processRuntimeId: formData.processRuntimeId, // 流程运行节点id
                  operator: getUserInfo().empId || '' // 操作人
                }
              }
            })
          }
        })
      }
    })
  }

  let param = {
    approvalActionList: [approvalActionObj],
    comment: val.description,
    tenantId: localStorage.getItem('tenantId'),
    transferPerson: val.empId // 转交人
  }
  if (btnsNum.value === 1) {
    // 前加签
    // const { code, data } = await processApproveTaskpreAddSignApi(param)
    let empIds = []
    let approvalName = []
    val.empId.forEach((item) => {
      empIds.push(item.id)
      approvalName.push({
        id: item.empNum,
        name: item.empName,
        type: 'EMP'
      })
    })

    let param = {
      tenantId: localStorage.getItem('tenantId'),
      comment: val.description,
      approvalActionList: [approvalActionObj],
      approvalNode: {
        nodeId: GenNonDuplicateID(3),
        nodeType: 'beforeSignNode',
        approvalFormData: {
          nodeName: t('keys.Front_endorsement') + t('keys.node'),
          valueContent: t('keys.Front_endorsement'),
          approvalType: val.approvalType,
          autoPassFlag: true,
          distinctType: 'NOT_DISTINCT',
          actionType: ['TRANSFER', 'APPROVE', 'REFUSE'],
          approvalMap: {
            APPROVAL_GROUP: [],
            DEPT: [],
            EMP: empIds,
            POST: [],
            VARIABLE_NODE: []
          },
          approvalName: approvalName
        }
      }
    }
    const { code, data } = await beforeSignApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.Front_endorsement') + t('keys.success'))
      goBack()
    }
  } else if (btnsNum.value === 2) {
    // const { code, data } = await agreeAndAddSignApi(param)
    let empIds = []
    let approvalName = []
    val.empId.forEach((item) => {
      empIds.push(item.id)
      approvalName.push({
        id: item.empNum,
        name: item.empName,
        type: 'EMP'
      })
    })

    let param = {
      tenantId: localStorage.getItem('tenantId'),
      comment: val.description,
      approvalActionList: [approvalActionObj],
      approvalNode: {
        nodeId: GenNonDuplicateID(3),
        nodeType: 'beforeSignNode',
        approvalFormData: {
          nodeName: t('keys.Approved_and_signed_later') + t('keys.node'),
          valueContent: t('keys.Approved_and_signed_later'),
          approvalType: val.approvalType,
          autoPassFlag: true,
          distinctType: 'NOT_DISTINCT',
          actionType: ['TRANSFER', 'APPROVE', 'REFUSE'],
          approvalMap: {
            APPROVAL_GROUP: [],
            DEPT: [],
            EMP: empIds,
            POST: [],
            VARIABLE_NODE: []
          },
          approvalName: approvalName
        }
      }
    }
    const { code, data } = await afterSignApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.Approved_and_signed_later') + t('keys.success'))
      goBack()
    }
  } else if (btnsNum.value === 3) {
    const { code, data } = await processApproveTasktRansferApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.passed_on'))
      goBack()
    }
  } else if (btnsNum.value === 4) {
    const { code, data } = await processApproveTaskCcApi(param)
    if (code === ERR_OK) {
      ElMessage.success(t('keys.Cc') + t('keys.success'))
      goBack()
    }
  }
}

/**
 * 生成一个用不重复的ID
 */
const GenNonDuplicateID = (randomLength) => {
  let idStr = Date.now().toString(36)
  idStr += Math.random()
    .toString(36)
    .substr(2, randomLength)
  return idStr
}
const goBack = () => {
  setTimeout(() => {
    window.history.back(-1)
  }, 300)
}
const dialogObj = reactive({
  visible: false
})
const flowchartShow = () => {
  dialogObj.visible = true
}
</script>
<style lang="scss" scoped>
.mt20 {
  margin-top: 20px;
}
.cont {
  width: 100%;
  height: calc((100vh - 82px));
  display: flex;
  flex-direction: row;
  .cont_left {
    width: 80%;
    margin-bottom: -16px;
    overflow: hidden;
    overflow-x: hidden;
    overflow-y: scroll;
    padding: 0px 0 16px 0px;
    &::-webkit-scrollbar {
      height: 5px;
      width: 5px;
    }
    &::-webkit-scrollbar-corner {
      background: #204754;
    }
    &::-webkit-scrollbar-thumb {
      background: #ccc;
      border-radius: 10px;
    }
    &::-webkit-scrollbar-track {
      background: #fff;
      border-radius: 2px;
    }
  }
  .cont_right {
    width: 392px;
    position: relative;
    .cont_right_s {
      height: 100%;
      margin-bottom: -16px;
      margin-right: -16px;
      overflow: auto;
      overflow-x: hidden;
      overflow-y: scroll;
      padding: 16px 0 16px 16px;
      border-left: 1px var(--el-border-color) var(--el-border-style);
      position: relative;
      &::-webkit-scrollbar {
        height: 5px;
        width: 5px;
      }
      &::-webkit-scrollbar-corner {
        background: #204754;
      }
      &::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 10px;
      }
      &::-webkit-scrollbar-track {
        background: #fff;
        border-radius: 2px;
      }
      .contract_base_title {
        font-weight: 550;
        margin-bottom: 16px;
      }
      .cont_right_title {
        width: 100%;
        margin-bottom: 24px;
        .cont_right_t_p,
        .cont_right_t_t {
          font-size: 14px;
          font-weight: 400;
          color: #666666;
          line-height: 22px;
          span {
            margin-left: 10px;
            font-weight: none;
          }
        }
      }
      .approval_record {
        max-height: 500px;
        overflow-y: auto;
        overflow-x: hidden;
        padding: 16px 16px 0 22px;
        margin-left: -20px;
        position: relative;
        cursor: pointer;
        &::-webkit-scrollbar {
          height: 5px;
          width: 5px;
        }
        &::-webkit-scrollbar-corner {
          background: #204754;
        }
        &::-webkit-scrollbar-thumb {
          background: #ccc;
          border-radius: 10px;
        }
        &::-webkit-scrollbar-track {
          background: #fff;
          border-radius: 2px;
        }
        :deep(.el-timeline-item__timestamp.is-top) {
          font-size: 14px;
          font-weight: 550;
          color: #333;
        }
        .timeline_card {
          width: 308px;
          padding: 12px;
          background: #fafafa;
          margin-bottom: 8px;
        }
        .timeline_title {
          .timeline_title_l {
            font-weight: 400;
            color: #333333;
            line-height: 18px;
            font-size: 12px;
            margin-bottom: 8px;
            margin-top: 4px;
            span {
              color: #999999;
              margin-left: 8px;
            }
          }
          .timeline_title_lb {
            margin-bottom: 0;
          }
          .timeline_title_c {
            color: #666666;
            font-size: 12px;
            margin-bottom: 8px;
          }
          .timeline_title_cSuccess {
            color: #48d000;
          }
          .timeline_title_cError {
            color: red;
          }
          .timeline_title_r {
            width: 100%;
            color: #666666;
            line-height: 18px;
            font-size: 12px;
            word-wrap: break-word;
            display: flex;
            flex-direction: row;
            .timeline_title_r_ctitle {
              font-size: 12px;
              width: 20%;
            }
            .timeline_title_r_comm {
              word-wrap: break-word;
              width: 80%;
            }
          }
        }
      }
      .showbpmn {
        margin: 10px;
        margin-bottom: 100px;
        margin-left: 45px;
      }
    }

    .botm_btns {
      position: absolute;
      right: -16px;
      bottom: -32px;
      left: 1px;
      height: 64px;
      background: #fff;
      border-top: 1px var(--el-border-color) var(--el-border-style);
      border-left: 0px var(--el-border-color) var(--el-border-style);
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      align-items: center;
      .refuse {
        margin-right: 12px;
      }
      .approval {
        margin-right: 12px;
      }
    }
  }
}
.moreBtn {
  margin-right: 12px;
}
</style>
